<template>
  <div>
    <img @click="gologin" class="wx-img" src="~@/static/images/wxImg.png" alt />
    <span class="wx-desc">微信登录</span>
  </div>
</template>

<script>
import { accredit } from '~/api/identity'
import { getWeChatMessage } from '~/api/colleges'
import ls from 'store2'
export default {
  props: {},
  mounted: function() {
    this.codes = this.getUrlParam('code')
    if (!ls.get('wxopen_id')) {
      this.getCode()
    }
    if (!ls.get('wxuniond') && this.getUrlParam('code')) {
      this.getWxMsg()
    }
  },
  methods: {
    gologin() {
      let uniond = ls.get('wxuniond')
      this.userAccredit(uniond)
    },
    getCode() {
      // 非静默授权，第一次有弹框
      let appID = process.env.workAppid
      const code = this.getUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href
      if (code == null || code === '') {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=` + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
        setTimeout(() => {
          this.getWxMsg()
        }, 1000)
      } else {
        this.codes = code
        this.getWxMsg()
      }
    },
    getWxMsg() {
      getWeChatMessage(this.codes)
        .then((res) => {
          if (res.code == 0) {
            let uniond = res.data.unionid
            let openid = res.data.openid
            ls.set('wxopen_id', openid)
            ls.set('wxuniond', uniond)
          }
        })
        .catch((error) => {})
    },
    userAccredit(uniond) {
      accredit({
        unionId: uniond,
      })
        .then((res) => {
          if (res.code == 0) {
            if (res.data) {
              let token = res.data.accessToken
              let userData = res.data
              let uidVoid = res.data.userVoId
              ls.set('userType', res.data.userType)
              ls.set('tokensyxk', token)
              ls.set('yxkData', userData)
              ls.set('userVoId', uidVoid)
              if (this.$route.query.returnMall) {
                let uri = decodeURIComponent(this.$route.query.returnMall)
                let urls = uri + 'sx_uid=' + ls.get('userVoId') + '&sx_token=' + ls.get('tokensyxk') + '&open_id=' + ls.get('wxopen_id')
                window.location.replace(urls)
              } else {
                let goRoute = sessionStorage.getItem('goesRouter')
                if (goRoute) {
                  goRoute = JSON.parse(sessionStorage.getItem('goesRouter'))
                  if (goRoute) {
                    sessionStorage.clear()
                    if (goRoute.category === 'user') {
                      this.goRoutes('../user')
                    } else if (goRoute.category === 'home') {
                      this.goRoutes('../home')
                    } else if (goRoute.category === 'vip') {
                      this.goRoutes('../vipUserRoute/openVip?isJustIn=true')
                    }
                  } else {
                    this.goRoutes('../user')
                  }
                } else {
                  this.goRoutes('../user')
                }
              }
            }
          } else {
            if (this.$route.query.returnMall) {
              this.mallGoLogin('bindLogin', this.$route.query.returnMall)
            } else {
              this.commonJs.gopush('bindLogin')
            }
          }
        })
        .catch(() => {})
    },
    goRoutes(routerName) {
      this.$router.replace({
        path: '../' + routerName,
      })
    },
    mallGoLogin(routerName, queryData) {
      this.$router.push({
        path: routerName,
        query: {
          returnMall: queryData,
        },
      })
    },
    getUrlParam: function(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    },
  },
}
</script>

<style scoped lang="less">
.wx-img {
  display: block;
  width: 1rem;
  height: 1rem;
  margin: 1rem auto 0;
}
.wx-desc {
  display: block;
  width: 100%;
  text-align: center;
  font-size: 0.24rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(153, 153, 153, 1);
  line-height: 0.4rem;
}
</style>
